package com.base.cn.platform.os.controller.web.user.login;

import com.base.cn.platform.os.common.WebBaseController;
import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.ProfileType;
import com.base.cn.platform.os.common.utils.user.UserExpandFrom;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.common.utils.web.thirdLogin.QQLoginUtils;
import com.base.cn.platform.os.common.utils.web.thirdLogin.WXLoginUtils;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.user.user.CuserProfileService;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Map;
import java.util.TreeMap;

/**
 * 用户第三方登录
 * @Author zjh
 * @Description //TODO
 * @Date 2018/8/25 12:00
 */
@Controller
@RequestMapping("/web/thirdLogin")
@Slf4j
public class WebThirdLoginController extends WebBaseController {

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CuserProfileService cuserProfileService;
    @Autowired
    private LoginUserData loginUserData;

    /**
     * 跳转第三方登录
     * @param appType 类型，QQ、WEIXIN
     * @return 跳转
     */
    @RequestMapping("/authLogin")
    public String authLogin(HttpServletRequest request,
                            @RequestParam("appType") String appType,RedirectAttributes redirectAttributes) throws Exception {
        String callBack = null;
        if(appType.equals(ProfileType.QQ.toString())){//QQ登录
            TreeMap<String,String> qqConfigMap = sysConfigService.getSysConfigContext(ConfigName.QQLOGIN);
            callBack = QQLoginUtils.getAuthorizeURL(request,qqConfigMap.get("appId"),qqConfigMap.get("appKey"),qqConfigMap.get("pcUrl"));
        }
        if(appType.equals(ProfileType.WEIXIN.toString())){//微信登录
            TreeMap<String,String> wxConfigMap = sysConfigService.getSysConfigContext(ConfigName.WXLOGIN);
            String appid= wxConfigMap.get("pcOpenAppId");//开放平台PC应用的AppId;
            String redirect_uri = wxConfigMap.get("pcUrl");//PC登录回调
            callBack = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appid;
            callBack += "&redirect_uri="+ URLEncoder.encode(redirect_uri,"utf-8") + "&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
        }
        return redirect(request,callBack);
    }

    /**
     * QQ登录回调
     * @param request
     * @return
     */
    @RequestMapping("/qqLoginCallback")
    public String qqLoginCallback(HttpServletRequest request,
                                  HttpServletResponse response,
                                  RedirectAttributes redirectAttributes) throws Exception{
        AccessToken accessTokenObj = new Oauth().getAccessTokenByRequest(request);
        //验证回调失败，则跳转登录页面
        if (ObjectUtils.isEmpty(accessTokenObj) || accessTokenObj.getAccessToken().equals("")) {
            return redirect(request,"/web/user/login");
        }else{
            String accessToken = accessTokenObj.getAccessToken();
            String unionId = QQLoginUtils.getUnionId(accessToken);
            if(StringUtils.isEmpty(unionId)){
                return redirect(request,"/web/user/login");
            }
            //保存第三方登录数据
            Map<String,Object> resultMap= cuserProfileService.saveUserProfile(QQLoginUtils.getQQProfileUser(accessToken,unionId), UserExpandFrom.pcThirdQQ.getKey());
            if(!ResultUtil.getSuccess(resultMap)){
                redirectAttributes.addAttribute("message",ResultUtil.getMessage(resultMap));
                return redirect(request,"/web/user/login");
            }
            resultMap = loginUserData.setUserData(request,response,resultMap,"false");
            String url = (String)resultMap.get("url");
            return toUrl(request,url);
        }
    }

    /**
     * 微信登录回调
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/weiXinLoginCallback")
    public String weiXinLoginCallback(HttpServletRequest request,HttpServletResponse response,
                                      RedirectAttributes redirectAttributes) throws Exception{
        String code = request.getParameter("code");
        if (StringUtils.isNotEmpty(code)) {
            TreeMap<String,String> wxConfigMap = sysConfigService.getSysConfigContext(ConfigName.WXLOGIN);
            String pcOpenAppId = wxConfigMap.get("pcOpenAppId");//微信开放平台PC应用appId
            String pcOpenSecret= wxConfigMap.get("pcOpenSecret");// 微信开放平台PC应用secret
            //微信的openId和accessToken
            Map<String,String> map = WXLoginUtils.getAccessTokenAndOpendId(pcOpenAppId,pcOpenSecret,code);
            String openId = map.get("openId");
            log.info("============================openId:"+openId);
            String accessToken = map.get("accessToken");
            log.info("============================accessToken:"+accessToken);
            if(StringUtils.isNotEmpty(openId) && StringUtils.isNotEmpty(accessToken)) {
                ////保存第三方登录数据
                Map<String,Object> userProfile = WXLoginUtils.getWxUserProfile(openId,accessToken);
                userProfile.put("openId",openId);
                Map<String,Object> resultMap= cuserProfileService.saveUserProfile(userProfile, UserExpandFrom.pcThirdWeiXin.getKey());
                if(!ResultUtil.getSuccess(resultMap)){
                    redirectAttributes.addAttribute("message",ResultUtil.getMessage(resultMap));
                    return redirect(request,"/web/user/login");
                }
                resultMap = loginUserData.setUserData(request,response,resultMap,"false");
                String url = (String)resultMap.get("url");
                return toUrl(request,url);
            }
        }
        return redirect(request,"/web/user/login");
    }

    /**
     * 跳转
     * @param request
     * @param url
     * @return
     */
    private String toUrl(HttpServletRequest request,String url){
        if(StringUtils.isEmpty(url)){//
            url = WebUtils.getCookie(request, CommonConstants.REDIRECT);
            if(StringUtils.isEmpty(url)){
                url = "/web/uc/course/user/index";
            }
            return redirect(request,url);
        }else{
            return redirect(request,url);
        }
    }

}
